package tech.aistar.corejava.exam.nio;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.Date;
import java.util.Iterator;
import java.util.Scanner;
import java.util.Set;

/**
 * @author success
 * @version 1.0
 * @description:本类用来演示:
 * @date 2019/8/5 0005
 */
public class NioClient {
    public static void main(String[] args) throws IOException {
        System.out.println("客户端已经启动...");
        //1、创建通道
        SocketChannel sChannel = SocketChannel.open(new InetSocketAddress("127.0.0.1",8888));
        //2、切换异步非阻塞
        sChannel.configureBlocking(false);
        //3、指定缓冲区大小
        ByteBuffer allocate = ByteBuffer.allocate(1024);

        Scanner scanner = new Scanner(System.in);
        System.out.println("请输入内容：");
        while (scanner.hasNext()){
            System.out.println("请输入内容：");
            String str = scanner.next();
            allocate.put((new Date().toString()+"\n"+str).getBytes());
            //4、切换到读取模式
            allocate.flip();
            sChannel.write(allocate);
            allocate.clear();

        }
        sChannel.close();

    }
}
class NioServer{
    public static void main(String[] args) throws IOException {
        System.out.println("服务端已经启动...");
        //1、创建通道
        ServerSocketChannel sChannel = ServerSocketChannel.open();
        //2、切换异步非阻塞
        sChannel.configureBlocking(false);
        //3、绑定连接
        sChannel.bind(new InetSocketAddress(8888));
        //4、获取选择器
        Selector selector =Selector.open();
        //5、将通道注册到选择器，并且"指定监听接受事件"。
        sChannel.register(selector, SelectionKey.OP_ACCEPT);
        //6、轮训式 获取选择"已经准备就绪"的事件
        while (selector.select()>0){
            // 7.获取当前选择器所有注册的"选择键(已经就绪的监听事件)"
            Iterator<SelectionKey> iterator = selector.selectedKeys().iterator();
            while(iterator.hasNext()){
                //8.获取准备就绪的事件
                SelectionKey sk = iterator.next();
                //9.判断具体是什么事件准备就绪
                if(sk.isAcceptable()){
                    // 10.若"接受就绪",获取客户端连接
                    SocketChannel socketChannel = sChannel.accept();
                    //11.设置阻塞模式
                    socketChannel.configureBlocking(false);
                    //12.将该通道注册到服务器上
                    socketChannel.register(selector, SelectionKey.OP_READ);
                }else if(sk.isReadable()){
                    // 13.获取当前选择器"就绪" 状态的通道
                    SocketChannel socketChannel=(SocketChannel)sk.channel();
                    // 14.读取数据
                    ByteBuffer buffer = ByteBuffer.allocate(1024);
                    int len=0;
                    while ((len=socketChannel.read(buffer))>0){
                        buffer.flip();
                        System.out.println(new String(buffer.array(),0,len));
                        buffer.clear();
                    }
                }
            }

            iterator.remove();
        }
    }
}

class NNserver{
    public static void main(String[] args) throws IOException {
        ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
        serverSocketChannel.bind(new InetSocketAddress(8888));
        serverSocketChannel.configureBlocking(false); //设置服务端操作都是非阻塞的

        Selector selector = Selector.open(); //选择器
        serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT); //对客户端的accept事件关心

        while (true) {
            System.out.println("before===");
            selector.select(); //会阻塞住，直到有事件触发
            System.out.println("===");

            Set<SelectionKey> selectionKeys = selector.selectedKeys(); //看下有哪些事件被触发了
            System.out.println("selectionKeys:" + selectionKeys);

            Iterator<SelectionKey> iterator = selectionKeys.iterator();
            while (iterator.hasNext()) {
                SelectionKey key = iterator.next();

                if (key.isAcceptable()) {
                    //客户端 accept被触发了
                    ServerSocketChannel serverChannel = (ServerSocketChannel)key.channel();

                    SocketChannel clientChannel = serverChannel.accept();
                    System.out.println("channel is acceptable");
                    clientChannel.configureBlocking(false);

                    //客户端channel注册OP_WRITE事件
                    clientChannel.register(selector, SelectionKey.OP_WRITE);
                } else if (key.isWritable()) {
                    //客户端可以往里写数据了

                    System.out.println("channel is writeable");
                    String data = "hello world\n";

                    //注意这里的是客户端的channel，因为是使用客户端channel注册OP_WRITE事件
                    SocketChannel clientChannel = (SocketChannel)key.channel();
                    ByteBuffer buffer = ByteBuffer.allocate(data.length());
                    buffer.put(data.getBytes());
                    buffer.flip();
                    clientChannel.write(buffer);
                }
                key.cancel(); //取消事件
                iterator.remove();
            }
        }
    }
}